﻿/*  Copyright © 2012 Matthew David Elgert - mdelgert@yahoo.com
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation; either version 2.1 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */

using System;
using System.IO;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;

namespace BLL
{

    public static class SQLBackup
    {

        public static void BackupDBs()
        {
            using (DataTable dt = Common.GetDBNames())
            {
                foreach (DataRow row in dt.Rows)
                {
                    BackupDB(row[0].ToString());
                }
            }
        }

        private static void BackupDB(string DBName)
        {

            Log.Msg("Backup DB " + DBName + " begin");
            Common.ShowProgress(true);

            string DBFullPath = Common.GetDBBackupFullPath(DBName);

            try
            {
                using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString()))
                {
                    string SQL = @"BACKUP DATABASE " + DBName + @" TO DISK = '" + DBFullPath + DBName + Common.GetTimeStamp() + ".bak'";
                    using (SqlCommand cmd = new SqlCommand(SQL, cnn))
                    {
                        cmd.CommandTimeout = Common.GetSQLCommandTimeout();
                        cnn.Open();
                        cmd.ExecuteNonQuery();
                        cmd.Dispose();
                        cnn.Close();
                    }
                }
                Common.ShowProgress(false);
                Log.Msg("Backup DB " + DBName + " success");
            }
            catch (System.Exception ex)
            {
                Log.Msg("Backup DB " + DBName + " failed");
                Log.Msg(ex.ToString(), true);
            }

        }

    }

}
